<template>
	<view class="content">
		<view class="text-area">
			<button @touchstart="startRecord" @touchend="endRecord">开始录音</button>
			<button @tap="playVoice">播放录音</button>

		</view>

		<view>
			{{txt}}
			{{text}}
		</view>

	</view>
</template>

<script>
	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.autoplay = true;
	export default {
		data() {
			return {
				voicePath: '',

				options: {}, // 语音转文字的设置

				text: '', // 识别的文字
				txt: '显示的文字', // 
				width: '', // 屏幕宽度

				zwz: false,
			}
		},
		onLoad() {
			let self = this;
			recorderManager.onStop(function(res) {
				console.log('recorder stop' + JSON.stringify(res));
				self.voicePath = res.tempFilePath; //回调录音地址
			});
		},
		methods: {
			// 开始录音
			startRecord() {
				console.log('开始录音');
				// 转文字

				recorderManager.start({
					duration: 180000 //录音时长
				});
				this.handleVoice()
			},
			// 录音结束
			endRecord(call) {
				console.log('录音结束');
				recorderManager.stop(call => {
					// 临时音频文件路径
					console.log(call.tempFilePath)
				});

				//上传音频
				// uni.uploadFile({
				// 	url: 'https',
				// 	filePath: call.tempFilePaths[0],
				// 	name: 'file',
				// 	success: (uploadFileRes) => {
				// 		console.log(uploadFileRes.data);
				// 		this.text = uploadFileRes.data;
				// 	}
				// });

			},

			// 播放录音
			playVoice() {
				console.log('播放录音');
				if (this.voicePath) {
					innerAudioContext.src = this.voicePath;
					innerAudioContext.play();
				}
			},

			// 录音转文字
			handleVoice() {
				console.log('语音输入')
				let _this = this;
				this.options.engine = 'baidu'
				this.options.punctuation = false; // 是否需要标点符号 
				this.options.timeout = 10 * 1000; //超时时间
				this.options.userInterface = false; // 是否显示语音界面
				plus.speech.startRecognize(this.options, (s) => {
					_this.text = s
					_this.zwz = true
					console.log(_this.text)
					plus.speech.stopRecognize(); // 关闭
				});
			},

		},
	}
</script>
